package com.bicntech.common.utils.file;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;

/**
 * 图片工具类
 *
 * @author : JMY
 * @create 2023/7/14 13:58
 */
@Slf4j
public class ImgUtils {

    /**
     * 判断文件是否图片
     */
    public static boolean isImage(MultipartFile file) {
        if(file.isEmpty()){
            return false;
        }
        String fileType = FileUtil.getSuffix(file.getOriginalFilename());
        if(StrUtil.isBlank(fileType)) return false;
        if(Arrays.asList("JPG", "jpg", "png", "gif", "tif", "bmp", "jpeg").contains(fileType)){
            return true;
        }
        BufferedImage image = null;
        try {
            // 如果是spring中MultipartFile类型，则代码如下
            image = ImageIO.read(file.getInputStream());
            if(image == null || image.getWidth() <= 0 || image.getHeight()<= 0 ){
                return false;
            }
            return true;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
    }
}
